package client;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.Socket;

import event.Event;
import event.EventHandler;

public class PeerHandler implements Runnable {

	private final Socket mSocket;

	private DataOutputStream mDos;
	private DataInputStream mDis;

	private final EventManager<Event, EventHandler> mEventManager = new EventManager<Event, EventHandler>();

	private File mDefaultDirectory;

	public PeerHandler(Socket clientSocket) throws IOException {
		mSocket = clientSocket;

		mEventManager.register(new PeerFileRequestEventHandler());

		// Set the current working directory.
		mDefaultDirectory = new File("");

		mDis = new DataInputStream(mSocket.getInputStream());
		mDos = new DataOutputStream(mSocket.getOutputStream());
	}

	/*
	 * Handle the client requests.
	 */
	@Override
	public void run() {
		try {
			Event e = null;
			byte[] buffer = null;

			String parameters;
			int request, len;
			long packageOffset, packageSize;

			// while (mSocket.isConnected()) {
			// ------------------------------------------
			// This is the protocol for every message:
			// ------------------------------------------
			// (int) EVENT_TYPE
			// (long) OFFSET (offset of segment in TOTAL_LENGTH)
			// (long) TOTAL_LENGTH (total message length)
			// (int) SEGMENT_LENGTH (<= TOTAL_LENGTH)
			// (UTF) PARAMETER
			// (byte[]) BUFFER (of size SEGMENT_LENGTH)
			// ------------------------------------------

			request = mDis.readInt();
			packageOffset = mDis.readLong();
			packageSize = mDis.readLong();
			len = mDis.readInt();
			parameters = mDis.readUTF();

			if (len > 0) {
				buffer = new byte[len];
				mDis.readFully(buffer, 0, len);

				e = new Event(request, parameters, buffer, packageOffset,
						packageSize, mDos);
			} else {
				e = new Event(request, parameters, null, packageOffset,
						packageSize, mDos);
			}

			mEventManager.handle(e);
			// }
		} catch (IOException e) {
			// TODO handle client disconnect
			System.out.print("Client disconnected");
		}
	}

}
